<template>
  <!-- 订单完成情况统计表 -->
  <div class="orderEvaluateForm">
    <ContentWrap>
      <FormContainer :column="3">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
          <el-form-item prop="isMonth" label="查询方式">
            <el-select v-model="formData.isMonth" clearable placeholder="请选择查询方式" @change="handleChangeIsMonth">
              <el-option value="0" label="日" />
              <el-option value="1" label="月" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="formData.isMonth === '1'" prop="times" label="日期">
            <el-date-picker
              v-model="formData.times"
              type="monthrange"
              value-format="yyyy-MM-dd"
              range-separator="-"
              opt
              operator=">"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
              :limite="new Date()"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item v-if="formData.isMonth === '0'" prop="times" label="日期">
            <el-date-picker
              v-model="formData.times"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="-"
              opt
              operator=">"
              :limite="new Date()"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item prop="officeId" label="办事处">
            <OfficeOrDealerSelect v-model="formData.officeId" :obj="{value:'officeId',name:'officeName'}" :api-func="pageOrderDoneOffice" :time="formData.times" :disabled="disabled" placeholder="请选择办事处" filterable clearable></OfficeOrDealerSelect>
          </el-form-item>
          <el-form-item prop="dealerId" label="经销商名称">
            <OfficeOrDealerSelect v-model="formData.dealerId" :emit="formData.officeId" :obj="{value:'dealerId',name:'dealerName'}" :api-func="pageOrderDoneDealer" :others-raw="{officeId: formData.officeId}" :time="formData.times" :disabled="dealerDisabled" placeholder="请选择经销商" filterable clearable></OfficeOrDealerSelect>
          </el-form-item>
          <el-form-item prop="staffName" label="送装技师">
            <el-input v-model="formData.staffName" placeholder="请输入送装技师姓名" clearable />
          </el-form-item>

          <el-form-item prop="deliveryType" label="订单类型">
            <el-select v-model="formData.deliveryType" filterable clearable multiple placeholder="请选择订单类型">
              <el-option v-for="(item, index) of deliveryTypeList" :key="index" :value="item.dictCode" :label="item.dictName" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <Button @click="$refs.form.resetFields()">重置</Button>
            <Button type="primary" enter @click="queryHandle">查询</Button>
          </el-form-item>
        </el-form>
      </FormContainer>
      <div class="button-container" style="padding-top:0">
        <ExportPane :table-config="tableConfig" :other-raw="otherRaw" :data-source="selectedAry" :query-data-fun="queryHandle" filename="订单完成情况统计表">导出</ExportPane>
      </div>
      <table-box
        ref="table"
        no-request
        :table-config="tableConfig"
        :other-filters="otherFilters"
        :other-raw="otherRaw"
        @selection-change="selectionChange"
      >
        <el-table-column slot="before" type="selection" width="55"></el-table-column>
        <el-table-column slot="before" type="index" label="序号" width="55"></el-table-column>
      </table-box>
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import Button from '@/components/Button'
import ExportPane from '@/components/ExportPane'
import OfficeOrDealerSelect from '../components/officeOrDealerSelect'
import { pageOrderDoneOffice, pageOrderDoneDealer } from '@/api/serviceQuality'
import { filtersRaw, checkRange } from '@/utils'
import { ccDict } from '@/api/dataDict'
import Evaluate from './components/evaluate'

export default {
  name: 'OrderFinishReportForm',
  components: {
    ContentWrap,
    FormContainer,
    Button,
    ExportPane,
    OfficeOrDealerSelect
  },
  data() {
    const validatorTimes = (r, v, c) => {
      if (this.formData.isMonth === '0') {
        if (v instanceof Array && v.length === 2) {
        // 不超过四个月

          if (checkRange()(v, 4)) {
            c()
          } else {
            c(new Error('日期跨度不能大于四个月'))
          }
        } else {
          c(new Error('请选择日期'))
        }
      } else {
        c()
      }
    }
    return {
      pageOrderDoneOffice,
      pageOrderDoneDealer,
      otherFilters: [],
      otherRaw: {},
      formData: {
        isMonth: '',
        times: [],
        officeId: '',
        dealerId: '',
        staffName: '',
        deliveryType: ''
      },
      formRules: {
        isMonth: [{ required: true, message: '请选择查询方式', trigger: 'change' }],
        times: [{ required: true, type: 'array', message: '请选择日期', trigger: 'change' },
          { validator: validatorTimes, trigger: 'change' }]
      },
      tableConfig: {
        interfacePath: '/call-center/api/v1/reportOrderCompletion/page',
        pageFlag: true,
        hideFuncBar: true,
        // 表格字段动态配置
        setting: [
          {
            prop: 'officeId',
            label: '办事处编码',
            width: 110
          },
          {
            prop: 'officeName',
            label: '办事处',
            minWidth: 100
          },
          {
            prop: 'dealerId',
            label: '经销商编码',
            width: 110
          },
          {
            prop: 'dealerName',
            label: '经销商名称',
            minWidth: 110
          }, {
            prop: 'businessStatus',
            label: '经销商经营状态',
            minWidth: 140,
            propEnum: {
              appCode: 'call-center',
              domainCode: 'marketing',
              dictTypeCode: 'BUSINESS_STATUS'
            }
          },
          {
            prop: 'staffCode',
            label: '职员编码',
            minWidth: 140
          },
          {
            prop: 'staffName',
            label: '送装技师',
            minWidth: 100
          },
          {
            prop: 'staffPhone',
            label: '联系电话',
            minWidth: 100
          },
          {
            prop: 'grade',
            label: '技术等级',
            minWidth: 100
          },
          {
            prop: 'completionCount',
            label: '累计完成单量',
            minWidth: 130
          },
          {
            prop: 'appraiseNum',
            label: '评价完成单量',
            minWidth: 130
          },
          {
            prop: 'deliveryType',
            width: 120,
            label: '订单类型',
            propEnum: {
              appCode: 'call-center',
              domainCode: 'marketing',
              dictTypeCode: 'CC_ORDER_TYPE'
            }
          },
          {
            prop: 'serviceAttitude',
            label: '服务态度',
            minWidth: 100,
            formatData: v => this.com5Score(v.serviceAttitude, v.appraiseNum)
          },
          {
            prop: 'deliverySpeed',
            label: '送装速度',
            minWidth: 100,
            formatData: v => this.com5Score(v.deliverySpeed, v.appraiseNum)
          },
          {
            prop: 'installationQuality',
            label: '安装质量',
            minWidth: 100,
            formatData: v => this.com5Score(v.installationQuality, v.appraiseNum)
          },
          // {
          //   prop: 'satisfaction',
          //   label: '综合满意度',
          //   minWidth: 120,
          //   formatData: v => {
          //     const score = (v.serviceAttitude || 0) + (v.deliverySpeed || 0) + (v.installationQuality || 0)
          //     return this.com5Score(score / 3, v.appraiseNum)
          //   }
          // },
          {
            prop: 'satisfaction',
            width: 140,
            label: '综合满意度',
            formatData: v => {
              if (!v.appraiseNum) return 0
              return ((Number(v.serviceAttitude || 0) + Number(v.deliverySpeed || 0) + Number(v.installationQuality || 0)) / v.appraiseNum / 2 / 3 - (v.companyScore || 0)).toFixed(2)
            }
          },
          {
            prop: 'assessResult',
            label: '任职考核',
            minWidth: 120,
            propEnum: {
              domainCode: 'marketing',
              appCode: 'call-center',
              dictTypeCode: 'ASSESSMENT_RESULT'
            }
          }, {
            prop: 'companyScore',
            width: 120,
            label: '公司评分'
          }, {
            prop: 'rater',
            width: 140,
            label: '评分人'
          }, {
            prop: 'scoringTime',
            width: 140,
            label: '评分时间'
          }, {
            prop: '',
            width: 120,
            label: '操作',
            render: (_, row) => {
              if (row.rater) {
                return (
                  <span>已评分</span>
                )
              }
              return (
                <Evaluate staffPhone={row.staffPhone} onRefresh={this.queryHandle.bind(this, 'onPage')}></Evaluate>
              )
            }
          }]
      },
      selectedAry: [],
      deliveryTypeList: [] // 订单类型列表
    }
  },
  computed: {
    disabled() {
      return !(this.formData.times instanceof Array) || this.formData.times.length !== 2 || (this.formData.isMonth === '0' && !checkRange()(this.formData.times, 4))
    },
    dealerDisabled() {
      return this.disabled || !this.formData.officeId
    }
  },
  created() {
    if (!this.$isCC) {
      this.$set(this.formRules, 'officeId', [{ required: true, message: '请选择办事处', trigger: 'change' }])
      this.pageOrderDoneOffice = (...args) => {
        return pageOrderDoneOffice.call(this, ...args, false).then(res => {
          return res.filter(e => this.$store.getters.otherCode.includes(e.officeId))
        })
      }
    }
    this.getDeliveryTypeList()
  },
  methods: {
    // 获取订单类型字典
    getDeliveryTypeList() {
      ccDict('CC_ORDER_TYPE').then(res => {
        this.deliveryTypeList = res.data
      })
    },
    // 查询
    queryHandle(type) {
      return this.$refs.form.validate().then(() => {
        const list = []
        const otherRaw = {}
        const eq = ['officeId', 'dealerId']
        for (const [k, v] of Object.entries(this.formData)) {
          if (v === undefined || v === null || v === '' || (v instanceof Array && v.length <= 0)) {
            continue
          }

          if (k === 'times') {
            if (this.formData.isMonth === '1') {
              otherRaw.startDate = v[0].split('-').filter((m, i) => i < 2).join('-') // 时间格式化 2020-06
              otherRaw.endDate = v[1].split('-').filter((m, i) => i < 2).join('-')
            } else {
              otherRaw.startDate = v[0]
              otherRaw.endDate = v[1]
            }
          } else if (k === 'isMonth') {
            otherRaw.isMonth = v
          } else if (k === 'deliveryType') {
            list.push(filtersRaw(k, `[${v.join(',')}]`, 'in'))
          } else if (eq.includes(k)) {
            // otherRaw[k] = v
            list.push(filtersRaw(k, v, '='))
          } else {
            list.push(filtersRaw(k, v, 'like'))
          }
        }
        this.otherRaw = otherRaw
        this.otherFilters = list
        if (type !== 'export') {
          this.refreshTable()
        }
        return list
      }).catch(err => {
        console.error(err)
      })
    },
    // 刷新表格
    refreshTable(type) {
      this.$nextTick(() => {
        this.$refs.table.initTableData(type)
      })
    },
    // 表格选中事件
    selectionChange(val) {
      this.selectedAry = val
    },
    // 5分制
    com5Score(score, appraiseNum) {
      if (!appraiseNum) return 0
      return ((score || 0) / appraiseNum / 2).toFixed(2)
    },
    // 查询方式变更
    handleChangeIsMonth() {
      this.$set(this.formData, 'times', []) // 变更时清空日期值
    }
  }
}
</script>
<style lang='scss' module>
</style>
